<template>
  <div class="container">
    <div class="treeandlegend-content" v-show="closetree">
      <div class="tree-content">
        <el-input
                class="filter-condition"
                placeholder="输入关键字进行过滤"
                v-model="filterText">
        </el-input>
        <el-tree
                class="filter-tree"
                :data="data"
                show-checkbox
                :props="defaultProps"
                @check="setlayer"
                default-expand-all
                @node-drag-start="handleDragStart"
                @node-drag-enter="handleDragEnter"
                @node-drag-leave="handleDragLeave"
                @node-drag-over="handleDragOver"
                @node-drag-end="handleDragEnd"
                @node-drop="handleDrop"
                draggable
                :allow-drop="allowDrop"
                :allow-drag="allowDrag"
                :filter-node-method="filterNode"
                node-key="id"
                ref="tree">
          <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button
                  type="text"
                  size="mini"
                  v-if="data.allowdel"
                  @click="() => edit(data)">
            Edit
          </el-button>
          <el-button
                  type="text"
                  size="mini"
                  v-if="data.allowdel"
                  @click="() => remove(node, data)">
            Delete
          </el-button>
        </span>
      </span>
        </el-tree>
      </div>
    </div>

  </div>
</template>

<script>
  import measuretools from "./components/measuretools";
  import toolsformap from "./components/toolsformap"
  import timeline from './components/timeline';
  import landarrtibute from "./components/landarrtibute";
  import manylayerattribute from "./components/manylayerattribute";
  import analysisform from "./components/analysisform";
  import Map from 'ol/Map.js';
  import View from 'ol/View.js';
  import {FullScreen,ScaleLine, defaults as defaultControls} from 'ol/control';
  import {Group as LayerGroup} from 'ol/layer';
  import Draw from 'ol/interaction/Draw';
  import Feature from 'ol/Feature';
  import VectorSource from 'ol/source/Vector';
  import {Vector as VectorLayer} from 'ol/layer';
  import {Icon, Style,Text,Circle as CircleStyle} from 'ol/style';
  import GeoJSON from 'ol/format/GeoJSON';
  import {WFS} from 'ol/format';
  import {Fill, Stroke} from 'ol/style';
  import Projection from "ol/proj/Projection";
  import {defaults} from 'ol/control.js';
  import {getWidth, getTopLeft} from 'ol/extent.js';
  import TileLayer from 'ol/layer/Tile.js';
  import TileWMS from 'ol/source/TileWMS';
  import WMTS from 'ol/source/WMTS.js';
  import WMTSTileGrid from 'ol/tilegrid/WMTS.js';
  import MousePosition from 'ol/control/MousePosition';
  import {createStringXY} from 'ol/coordinate';
  import PluggableMap from 'ol/PluggableMap';
  import {getVectorContext} from 'ol/render';
  import {sortFeature} from "../../utils/map/countFeaturestype";
  import {getDictproperties, getLayerStyle, impShape} from "../../api/cydtRequest";
  import XYZ from "ol/source/XYZ"
  import {get as getProjection} from 'ol/proj';
  import MultiPolygon from 'ol/geom/MultiPolygon'
  import ImageWMS from 'ol/source/ImageWMS';
  import {Image as ImageLayer} from 'ol/layer';
  import {
    and as andFilter,
    equalTo as equalToFilter,
    like as likeFilter,
    intersects as intersectsFilter,
    or as orFilter
  } from 'ol/format/filter';
  import axios from "axios";
  import bus from "../../assets/js/eventBus"
  import { register } from 'ol/proj/proj4';
  import proj4 from 'proj4';
  //import {getPublicDataCatalogProperties,getDepartmentDataCatalogProperties,getPersonalDataCatalogProperties} from "@/api/api";
  import {getPublicDataCatalogProperties} from "../../api/cydtRequest";
  import {getDepartmentDataCatalogProperties} from "../../api/cydtRequest";
  import {getPersonalDataCatalogProperties} from "../../api/cydtRequest";
  import {dataShare} from "../../api/cydtRequest";
  import {dataDel} from "../../api/cydtRequest";
  proj4.defs("EPSG:4490", "+proj=longlat +ellps=GRS80 +no_defs");
  register(proj4);
  PluggableMap.prototype.getEventPixel = function (event) {
    const viewportPosition = this.viewport_.getBoundingClientRect();
    let size = [viewportPosition.width, viewportPosition.height];
    const view = this.getView();
    if (view) {
      size = view.getViewportSize_();
    }
    const eventPosition =
            //FIXME Are we really calling this with a TouchEvent anywhere?
            'changedTouches' in event
                    ? /** @type {TouchEvent} */ (event).changedTouches[0]
                    : /** @type {MouseEvent} */ (event);
    return [
      ((eventPosition.clientX - viewportPosition.left) * size[0]) /
      viewportPosition.width,
      ((eventPosition.clientY - viewportPosition.top) * size[1]) /
      viewportPosition.height
    ];
  };
  export default {
    name: "oneMap",
    components: {

    },
    props:['changepage'],
    data(){
      return{
        fullscreenLoading: false,
        formLabelWidth: '80px',
        maps:null,
        pagebtn:null,
        closetree:true,
        type:"",
        mapInfoLayer:null,
        vectorSource:null,
        filterText: '',
        data2: [{
          id: 1,
          label: '公共数据',
          serverurl:'',
          children: [{
            id: 4,
            label: '产业园区布局',
            serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
            layername:'xf:wj_cyyqbj2022',
          },
            {
              id: 9,
              label: '工业企业分布',
              serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
              layername:'xf:wjgyyd2022'
            },
            {
              id: 14,
              label: '2022年重大项目',
              serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
              layername:'xf:zdxm2022'
            },
            {
              id: 15,
              label: '现状用地分布',
              serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
              layername:'xf:wjxzydfb2022'
            },
            {
              id: 18,
              label: '9大重点产业',
              serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
              layername:'xf:wj95x92022'
            },
            {
              id: 19,
              label: '5张产业名片',
              serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
              layername:'xf:wj95x52022'
            },
            {
              id: 20,
              label: '可储备工业用地',
              serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
              layername:'xf:wjkcbgyyd2022'
            },
            {
              id: 21,
              label: '武进专精特新企业',
              serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
              layername:'xf:wjzjtx2022'
            },
              {
                  id: 22,
                  label: '武进低效用地',
                  serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
                  layername:'xf:wjdxyd2022'
              },
              {
                  id: 23,
                  label: '武进连片开发',
                  serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
                  layername:'xf:wjlpkf2022'
              }
          ]
        }, {
          id: 2,
          label: '科室数据',
          children: [{
                  id: 5,
                  label: '常州市总体规划',
                  serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
                  layername:'xf:czsztgh2011_2020'
              },{
            id: 6,
            label: '控制性详细规划',
            serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
            layername:'xf:wj_konggui2022'
          }
          ,
            {
              id: 10,
              label: '村镇建设控制区',
              serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
              layername:'xf:wj_czjskzq2022'
            },{
              id: 11,
              label: '基期地类',
              serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
              layername:'xf:wj_jqdl2022'
            }
            ,{
              id: 12,
              label: '建设用地管制区',
              serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
              layername:'xf:wj_jsydgzq2022'
            }
            ,{
              id: 13,
              label: '土地用途区',
              serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
              layername:'xf:wj_tdytq2022'
            }
            ,{
                  id: 16,
                  label: '基本农田保护区',
                  serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
                  layername:'xf:wj_jbntbhq2022'
              }

            ,{
              id: 17,
              label: '武进村庄规划',
              serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
              layername:'xf:wjczgh2018_2020'
            }
          ]
        },
         {
          id: 3,
          label: '个人数据',
          children: [{
            id: 7,
            label: '武进医疗设施',
            serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
            layername:'xf:wjylss2018_m'
          }]
        },
            {
                id: 24,
                label: '辅助图层',
                children: [{
                    id: 25,
                    label: '武进区镇界',
                    serverurl:'http://218.93.116.192:8087/geoserver/xf/wms',
                    layername:'xf:wjzjm'
                }]
            }

        ],
        data: [{
          id: 1,
          label: '公共数据',
          dragable:false,
          droptype:'refuse',
          allowdel:false,
          serverurl:'',
          children: []
        }, {
          id: 2,
          label: '科室数据',
          dragable:false,
          droptype:'refuse',
          allowdel:false,
          children: []
        },
          {
            id: 3,
            label: '个人数据',
            dragable:false,
            droptype:'refuse',
            allowdel:false,
            children: []
          }

        ],
        defaultProps: {
          children: 'children',
          dragable:false,
          droptype:'refuse',
          allowdel:false,
          label: 'label'
        },
        //layerCheckAdd,layerCheckDel用于存储左侧目录树的添加与删除图层
        layerCheckAdd:[],
        layerCheckDel:[],
        editStatus:false,

      }
    },
    created(){

    },
    watch: {
      filterText(val) {
        this.$refs.tree.filter(val);
      },
      changepage(newV,oldV){
        console.log(newV)
        var geojsonObject={}
        if(newV.btnum==1){
          /*this.pagebtn=1
           geojsonObject={"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[119.938243504,31.640018024],[119.938137872,31.639978024],[119.938135508,31.639982586],[119.938135085,31.639983415],[119.938135062,31.639983447],[119.9375174,31.639768312],[119.937469343,31.639762687],[119.937418664,31.639766535],[119.937376195,31.639777991],[119.937332031,31.639799671],[119.937331997,31.639799692],[119.937302857,31.639821767],[119.937274836,31.639858436],[119.937253378,31.63989263],[119.937253146,31.639893468],[119.937253123,31.639893511],[119.937144927,31.640283884],[119.937144982,31.640283888],[119.937219546,31.640297099],[119.937219275,31.640297977],[119.937137404,31.640551168],[119.937114864,31.640620876],[119.937067666,31.640766868],[119.937027803,31.64089017],[119.936896429,31.641304633],[119.936896417,31.641304685],[119.937588702,31.64154162],[119.938708178,31.641924752],[119.938708771,31.641923478],[119.938709159,31.641922644],[119.938941086,31.641426639],[119.938941476,31.641425806],[119.938196555,31.641172496],[119.938196509,31.64117248],[119.938196406,31.641172445],[119.938196424,31.641172409],[119.938315011,31.640930575],[119.938683793,31.640178508],[119.938684198,31.64017768],[119.938683982,31.640177605],[119.938566375,31.640136642],[119.938403202,31.640079807],[119.938403078,31.640079764],[119.938407352,31.64007042],[119.938407735,31.640069583],[119.938369802,31.640056921],[119.938356835,31.640052928],[119.938243504,31.640018024]]]},"properties":{"tdzl":"武进国家高新技术产业开发区龙域西路29号","yddw":"常州龙翔气弹簧股份有限公司","kid":"777777"}}]}
         this.addVectorlayer(geojsonObject)
          this.maps.getView().fit(geojsonObject.features[0])*/
        }
        if(newV.btnum==2){
          /*this.pagebtn=2
           geojsonObject ={"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Polygon","coordinates":[[[119.725162135,31.676535635],[119.725651966,31.676274615],[119.725474674,31.675989731],[119.724851792,31.676321652],[119.724784867,31.6762298],[119.724713262,31.676267955],[119.724277979,31.67567055],[119.723728106,31.675962966],[119.724230624,31.676652654],[119.722768842,31.677431571],[119.723111276,31.677901553],[119.725287799,31.676741768],[119.725162135,31.676535635]]]},"properties":{"LAYER":"2022省级","NAME":"武进国家农村产业融合发展示范园,（花木交易中心）","kid":"666666"}}]}
           this.addVectorlayer(geojsonObject)
           this.maps.getView().fit(geojsonObject.features[0])*/
        }
        if(newV.btnum==0){
          /*this.showdraw=true
          this.pagebtn=0*/
        }
    },
    },
    mounted() {
      let that=this
      that.getDataCatalog();
      bus.$on("publishshpsta", (data) => {
        console.log("publishshpsta:"+data)
        that.getDataCatalog();
      });
      bus.$on("publishdxfsta", (data) => {
        console.log('publishdxfsta:'+data)
        that.getDataCatalog();
      });

    },
    methods:{

      handleDragStart(node, ev) {
        console.log('drag start', node);
      },
      handleDragEnter(draggingNode, dropNode, ev) {
        console.log('tree drag enter: ', dropNode.label);
      },
      handleDragLeave(draggingNode, dropNode, ev) {
        console.log('tree drag leave: ', dropNode.label);
      },
      handleDragOver(draggingNode, dropNode, ev) {
        console.log('tree drag over: ', dropNode.label);
      },
      handleDragEnd(draggingNode, dropNode, dropType, ev) {
        console.log('tree drag end: ', dropNode && dropNode.label, dropType);
      },
      handleDrop(draggingNode, dropNode, dropType, ev) {
        let that=this;
        dataShare(draggingNode.label).then(response=>{
          if (response.code == 200) {
            that.$message({
              message: '恭喜你，这是一条成功消息',
              type: 'success'
            });
            that.getDataCatalog();
          }
        }).catch(e=>{
          that.$message({
            message:'数据分享失败',
            type:'danger'
          })
        });

        console.log('tree drop: ', dropNode.label, dropType);
      },
      allowDrop(draggingNode, dropNode, type) {
        if (dropNode.data.droptype === 'not-inner') {
          return type !== 'inner';
        } else {
          return false;
        }
      },
      allowDrag(draggingNode) {
        return draggingNode.data.dragable;
      },
      //图层编辑
      edit(data) {
        var that = this;
        var status = !that.editStatus;
        that.editStatus = status;
        //向右侧菜单传值
        var editLayerName = data.layername.substring(6);
        console.log(editLayerName);
        bus.$emit("editstatus", status);
        bus.$emit("layername", editLayerName);

      },


      remove(node, data) {
        dataDel(node.label).then(response=>{
          if (response.code == 200) {
            that.$message({
              message: '恭喜你，这是一条成功消息',
              type: 'success'
            });
          }
        }).catch(e=>{
          that.$message({
            message:'数据删除失败',
            type:'danger'
          })
        });
        const parent = node.parent;
        const children = parent.data.children || parent.data;
        const index = children.findIndex(d => d.id === data.id);
        children.splice(index, 1);
      },

      setlayer(val1,val2){
        var that=this
        that.layerCheckAdd=[];
        that.layerCheckDel=[];
        if(val2.checkedNodes.length>0){//目录树上有选择
          if('children' in val1){
            var cancelcheck=true
            val2.checkedNodes.forEach(function (arr) {
              if(val1.id==arr.id){
                for(let j=0;j<val1.children.length;j++){
                  var layerItemInfo={
                    id: val1.children[j].id,
                    label: val1.children[j].label,
                    serverurl:val1.children[j].serverurl,
                    layername:val1.children[j].layername
                  };
                  that.layerCheckAdd.splice(0,0,layerItemInfo)
                }
                cancelcheck=false
              }
            })
            if(cancelcheck){
              for(let j=0;j<val1.children.length;j++){
                var layerItemInfo={
                  id: val1.children[j].id,
                  label: val1.children[j].label,
                  serverurl:val1.children[j].serverurl,
                  layername:val1.children[j].layername
                };
                that.layerCheckDel.splice(0,0,layerItemInfo)
              }
            }
          }else{
            var cancelcheck=true
            val2.checkedNodes.forEach(function (arr) {
              if(val1.id==arr.id){
                var layerItemInfo={
                  id: val1.id,
                  label: val1.label,
                  serverurl:val1.serverurl,
                  layername:val1.layername
                };
                that.layerCheckAdd.splice(0,0,layerItemInfo)
                cancelcheck=false
              }
            })
            if(cancelcheck){
              var layerItemInfo={
                id: val1.id,
                label: val1.label,
                serverurl:val1.serverurl,
                layername:val1.layername
              };
              that.layerCheckDel.splice(0,0,layerItemInfo)
            }
          }

        }else{//目录树上没有选择，全部移除
          if('children' in val1){
            for(let j=0;j<val1.children.length;j++){
              //that.removelayerfrommap(val1.children[j])
              var layerItemInfo={
                id: val1.children[j].id,
                label: val1.children[j].label,
                serverurl:val1.children[j].serverurl,
                layername:val1.children[j].layername
              };
              that.layerCheckDel.splice(0,0,layerItemInfo)
            }
          }else{
            var layerItemInfo={
              id: val1.id,
              label: val1.label,
              serverurl:val1.serverurl,
              layername:val1.layername
            };

            that.layerCheckDel.splice(0,0,layerItemInfo)
          }
        }
        //向myMap-center传递数据
        var addLayerItems=[that.layerCheckAdd,that.layerCheckDel];
        //var delLayerItems=that.layerCheckDel;
        bus.$emit("send", addLayerItems);

      },

      filterNode(value, data) {
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      //获取目录树信息20221204WGC
      getDataCatalog(){

        let that=this
        var PublicDataCatalog = [];
        var DepartmentDataCatalog = [];
        var PersonalDataCatalog = [];
        that.data[0].children=[];
        that.data[1].children=[];
        that.data[2].children=[];
        var childID=3;
        //获取公共数据信息，参数无意义
        getPublicDataCatalogProperties({publiclayer: 'public'}).then(response=>{
          //that.PublicDataCatalog=response.data
          let list=response.data;
          list.forEach(item=>{
            childID++;
            that.data[0].children.push(
                    {
                      id: childID,
                      label: item.name,
                      dragable:false,
                      droptype:'refuse',
                      allowdel:false,
                      serverurl:item.server_url,
                      layername:item.layer_name
                    }
            )
          });
        }).catch(e=>{
            that.$message({
              message:'获取公共数据失败',
              type:'danger'
                    })
                });
        //获取部门数据信息，参数无意义
        getDepartmentDataCatalogProperties({departmentlayer: 'department'}).then(response=>{
          //that.DepartmentDataCatalog=response.data
          let list=response.data;
          list.forEach(item=>{
            childID++;
            console.log(item);
            that.data[1].children.push(
                    {
                      id: childID,
                      label: item.name,
                      dragable:false,
                      droptype:'not-inner',
                      allowdel:false,
                      serverurl:item.server_url,
                      layername:item.layer_name
                    }
            )
          });
        }).catch(e=>{
          that.$message({
            message:'获取部门数据失败',
            type:'danger'
          })
        });
        //获取个人数据信息，参数无意义
        getPersonalDataCatalogProperties({personallayer: 'personal'}).then(response=>{
          //that.PersonalDataCatalog=response.data
          let list=response.data;
          list.forEach(item=>{
            childID++;
            that.data[2].children.push(
                    {
                      id: childID,
                      label: item.name,
                      dragable:true,
                      droptype:'not-inner',
                      allowdel:true,
                      serverurl:item.server_url,
                      layername:item.layer_name
                    }
            )
          });
        }).catch(e=>{
          that.$message({
            message:'获取个人数据失败',
            type:'danger'
          })
        });


        /*
        getPublicDataCatalogProperties('public').then(r=>{
          if (r) {
            let list=r.data;
            list.forEach(item=>{
              childID++;
              that.data[0].children.push(
                      {
                        id: childID,
                        label: item[0],
                        serverurl:item[1],
                        layername:item[2]
                      }
              )
            });
          }
        });
        getDepartmentDataCatalogProperties('Department').then(r=>{
          if (r) {
            let list=r.data;
            list.forEach(item=>{
              childID++;
              that.data[1].children.push(
                      {
                        id: childID,
                        label: item[0],
                        serverurl:item[1],
                        layername:item[2]
                      }
              )
            });
          }
        });
        getPersonalDataCatalogProperties('Personal').then(r=>{
          if (r) {
            let list=r.data;
            list.forEach(item=>{
              childID++;
              that.data[2].children.push(
                      {
                        id: childID,
                        label: item[0],
                        serverurl:item[1],
                        layername:item[2]
                      }
              )
            });
          }
        });*/


        console.log(that.data);

      },



    }
  }
</script>

<style >
  @import 'myMap.scss';
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
</style>
